/**
 * LocalStorage And SessionStorage
 */
type storageType = 'local' | 'session';
/**
 * 设置缓存
 * @param {string} type 缓存类型 local session
 * @param {string} key 缓存key
 * @param {string} value 缓存value
 */
function setStorage(type: storageType, key: string, value: any) {
    if(typeof value === 'object') {
        value = JSON.stringify(value)
    }
    switch (type) {
        case 'local':
            localStorage.setItem(key, value);
            break;
        case 'session':
            sessionStorage.setItem(key, value);
            break;
    }
}
/**
 * 获取缓存
 * @param {string} type 缓存类型 local session
 * @param {string} key 缓存key
 */
function getStorage(type: storageType, key: string) {
    let value = null;
    switch (type) {
        case 'local':
            value = localStorage.getItem(key);
            break;
        case 'session':
            value = sessionStorage.getItem(key);
            break;
    }
    try {
        value = JSON.parse(value)
    } catch {}
    return value;
}

/**
 * 删除缓存
 * @param {string} type 缓存类型 local session
 * @param {string} key 缓存key
 */
function removeStorage(type: storageType, key: string) {
    switch (type) {
        case 'local':
            localStorage.removeItem(key);
            break;
        case 'session':
            sessionStorage.removeItem(key);
            break;
    }
}


// 清除所有缓存
function clearStorage() {
    localStorage.clear();
    sessionStorage.clear();
}

export default {
    setStorage,
    getStorage,
    removeStorage,
    clearStorage
}